package com.dongdongshop.index;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.TbUserService;
import com.dongdongshop.configresult.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.util.ShiroUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping("login")
public class LoginController {


    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private TbUserService tbUserService;

    @RequestMapping("xixi")
    @ResponseBody
    public boolean sendMessage(String phone){
        try {
            rocketMQTemplate.convertAndSend("SMS",phone);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @RequestMapping("enroll")
    @ResponseBody
    public Result enroll(TbUser user, String duanxi){
        try {
//        取出短信验证码
            String o = (String)redisTemplate.boundValueOps(user.getPhone()).get();
            if(!(o.equals(duanxi))){
                return Result.builResult(ResultEnum.ERROR);
            }
//        生成密码和盐
            ShiroUtils shiroUtils = new ShiroUtils();
            Map<String, Object> map = shiroUtils.getpwdsalt(user.getPassword());

            user.setSalt((String) map.get("salt"));
            user.setPassword((String) map.get("pwd"));
            user.setCreated(new Date());
            user.setUpdated(new Date());

            tbUserService.insertAll(user);

            return Result.builResult(ResultEnum.SUCCESS);
        }catch (Exception e){
            return Result.builResult(ResultEnum.ERROR);
        }
    }

//    用户名校验
    @RequestMapping("uname")
    @ResponseBody
    public boolean uname(String name){
        TbUser user = tbUserService.selectName(name);
        if(user == null){
            return true;
        }
        return false;
    }

}
